-- 
-- Please see the readme.txt file included with this distribution for 
-- attribution and copyright information.
--

local ref = nil;
local scale = 0;

--
--
-- TOKEN REFERENCE EVENT HANDLERS
--
--

function refDeleted(deleted)
	-- CLEAR REFERENCE
	ref = nil;
end

function refTargeted(targeted)
	window.onClientTargetingUpdate(targeted);
end

function refDrop(droppedon, draginfo)
	-- HANDLE DROPS
	CombatCommon.onDrop("ct", window.getDatabaseNode().getNodeName(), draginfo);
end

--
--
-- WORKER FUNCTIONS
--
--

function getReference()
	return ref;
end

function hasReference()
	if User.isHost() and ref then
		return true;
	end
	return false;
end

function isActive()
	if hasReference() then
		return ref.isActive();
	end
	return false;
end

function setActive(status)
	if hasReference() then
		ref.setActive(status);
	end
end

function setName(name)
	if hasReference() then
		ref.setName(name);
	end
end

function getScale()
	return scale;
end

function setScale(newscale)
	if hasReference() then
		-- ADJUST THE TOKEN SCALE AND TRACKING VARIABLE
		scale = newscale;
		ref.setScale(newscale);
		
		-- UPDATE THE SCALE WIDGET
		if scale == 1 then
			if scaleWidget then
				scaleWidget.setVisible(false);
			end
		else
			if not scaleWidget then		
				scaleWidget = addTextWidget("sheetlabelsmall", "0");
				scaleWidget.setFrame("tempmodmini", 4, 1, 6, 3);
				scaleWidget.setPosition("topright", -2, 2);
			end
			scaleWidget.setVisible(true);
			scaleWidget.setText(scale);
		end
	end
end

function updateUnderlay()
	-- VALIDATE
	if not hasReference() then
		return;
	end
	
	-- SETUP
	local nodeCTEntry = window.getDatabaseNode();
	local space = math.ceil(NodeManager.get(nodeCTEntry, "space", 1)) / 2;
	local reach = math.ceil(NodeManager.get(nodeCTEntry, "reach", 1)) + space;
	local percent_wounded = 0;
	if NodeManager.get(nodeCTEntry, "hp", 0) > 0 then
		percent_wounded = NodeManager.get(nodeCTEntry, "wounds", 0) / NodeManager.get(nodeCTEntry, "hp", 0);
	end
			
	-- REMOVE PREVIOUS UNDERLAYS
	ref.removeAllUnderlays();

	-- ADD HOVER UNDERLAY
	if NodeManager.get(nodeCTEntry, "type", "") == "pc" then
		ref.addUnderlay(reach, "4f000000", "hover");
	else
		ref.addUnderlay(reach, "4f000000", "hover,gmonly");
	end

	-- ADD FACTION/HEALTH UNDERLAY
	local sFaction = NodeManager.get(nodeCTEntry, "friendfoe", "");
	if sFaction == "friend" then
		if percent_wounded >= 1 then
			ref.addUnderlay(space, "4f002200");
		elseif percent_wounded >= .5 and percent_wounded < 1 then
			ref.addUnderlay(space, "4f006600");
		else
			ref.addUnderlay(space, "2f00ff00");
		end
	elseif sFaction == "foe" then
		if percent_wounded >= 1 then
			ref.addUnderlay(space, "4f220000");
		elseif percent_wounded >= .5 and percent_wounded < 1 then
			ref.addUnderlay(space, "4f660000");
		else
			ref.addUnderlay(space, "2fff0000");
		end
	elseif sFaction == "neutral" then
		if percent_wounded >= 1 then
			ref.addUnderlay(space, "4f222200");
		elseif percent_wounded >= .5 and percent_wounded < 1 then
			ref.addUnderlay(space, "4f666600");
		else
			ref.addUnderlay(space, "2fffff00");
		end
	end
end

function drawAura(aurasize, tokensize)
	-- VALIDATE
	if not hasReference() then
		return;
	end
	
	-- REMOVE PREVIOUS UNDERLAYS
	ref.removeAllUnderlays();

	-- ADD AURA UNDERLAY
	local space = math.ceil(tokensize) / 2;
	ref.addUnderlay(space + aurasize, "4f0000ff", "gmonly");
end

function updateVisibility()
	-- VALIDATE
	if not hasReference() then
		return;
	end
	
	-- SET VISIBILITY BASED ON TOKEN TYPE AND CT VISIBILITY
	if window.type.getValue() == "pc" then
		ref.setVisible(true);
	else
		if window.show_npc.getState() then
			ref.setVisible(nil);
		else
			ref.setVisible(false);
		end
	end
end

function acquireReference(dropref)
	-- VALIDATE
	if not dropref then
		return;
	end
	
	-- Update the tokeninstance ref variable
	if ref and ref ~= dropref then
		ref.delete();
	end
	ref = dropref;

	-- Add callback handlers to clear the variable and to handle drops
	ref.onDelete = refDeleted;
	ref.onDrop = refDrop;

	-- If host, then we have more work to do
	if User.isHost() then
		ref.onTargetUpdate = refTargeted;

		ref.setTargetable(true);
		ref.setActivable(true);
		if window.type.getValue() == "pc" then
			ref.setVisible(true);
		else
			ref.setModifiable(false);
			updateVisibility();
		end

		ref.setActive(window.active.getState());
		ref.setName(window.name.getValue());

		window.tokenrefid.setValue(ref.getId());
		window.tokenrefnode.setValue(ref.getContainerNode().getNodeName());

		updateUnderlay();

		scale = ref.getScale();

		return true;
	end
end

function deleteReference()
	if ref then
		ref.delete();
		ref = nil;
	end
end

--
--
-- CT TOKEN EVENT HANDLERS
--
--

function onDrop(x, y, draginfo)
	if User.isHost() then
		if draginfo.isType("token") then
			local prototype, dropref = draginfo.getTokenData();
			setPrototype(prototype);
			return acquireReference(dropref);
		end
		if draginfo.isType("number") then
			return window.wounds.onDrop(x, y, draginfo);
		end
	end
end

function onDrag(button, x, y, draginfo)
	if not User.isHost() then
		return false;
	end
end

function onDragEnd(draginfo)
	if User.isHost() then
		local prototype, dropref = draginfo.getTokenData();
		return acquireReference(dropref);
	end
end

function onClickDown(button, x, y)
	return true;
end

function onClickRelease(button, x, y)
	-- LEFT CLICK TO SET TOKEN ACTIVE
	if button == 1 then
		if Input.isShiftPressed() then
			local nodeActiveCT = CombatCommon.getActiveCT();
			if nodeActiveCT then
				TargetingManager.toggleTarget("host", nodeActiveCT.getNodeName(), window.getDatabaseNode().getNodeName());
			end
		else
			setActive(not isActive());
		end
	
	-- RIGHT CLICK TO RESET SCALE
	else
		setScale(1.0);
	end

	return true;
end

function onWheel(notches)

	-- DETERMINE NEW SCALE
	if Input.isControlPressed() then
		newscale = math.floor(getScale() + notches);
		if newscale < 1 then
			newscale = 1;
		end
	else
		newscale = getScale() + notches*0.1;
		if newscale < 0.1 then
			newscale = 0.1;
		end
	end
	
	-- SET TO NEW SCALE
	setScale(newscale);

	return true;
end
